package com.trytech.mongoocrawler.common.transport.protocol;

import com.alibaba.fastjson.JSONObject;

import java.io.UnsupportedEncodingException;

/**
 * @author jiangtao@meituan.com
 * @since: Created on 2018年04月22日
 */
public class CrawlerTransferProtocol<T extends AbstractProtocol> {
    private int type;

    private Class<T> cls;
    private T content;

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    public Class<T> getCls() {
        return cls;
    }

    public void setCls(Class<T> cls) {
        this.cls = cls;
    }
    public T getContent() {
        return content;
    }

    public void setContent(T content) {
        this.content = content;
    }

    public byte toTypeByte() throws Exception {
        switch (type) {
            case 0:
                return 0x0;
            case 1:
                return 0x1;
            case 2:
                return 0x2;
            case 3:
                return 0x3;
            default:
                throw new Exception("协议解析错误");
        }
    }

    public int getContentLen() {
        return JSONObject.toJSONString(content).getBytes().length;
    }

    public byte[] toContentBytes() throws Exception {
        try {
            return JSONObject.toJSONString(content).getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new Exception("内容解析错误");
        }
    }
}
